<template>
	<page-layout class="page">
		<pure-gap size="12px"></pure-gap>

		<view class="pj-padding-sides">
			<!-- 基础使用 -->
			<pj-demo title="基础使用">
				<pure-upload-grid
					:list="list"
					@onChoose="handleChoose"
					@onDelete="handleDelete"
				></pure-upload-grid>
			</pj-demo>

			<!-- 上传 -->
			<pure-button
				text="模拟上传"
				block
				theme="primary"
				@onClick="handleUpload"
			></pure-button>
		</view>

		<pure-gap size="12px"></pure-gap>
	</page-layout>
</template>

<script setup>
	import { ref, computed, reactive } from "vue";
	import { onLoad, onReady, onShow } from "@dcloudio/uni-app";

	// 文件列表
	const list = ref([
		{
			status: "waiting",
			path: "/static/images/w_1.jpeg",
			progress: 0
		},
		{
			status: "waiting",
			path: "/static/images/w_2.jpeg",
			progress: 0
		},
		{
			status: "waiting",
			path: "/static/images/w_3.jpeg",
			progress: 0
		},
		{
			status: "waiting",
			path: "/static/images/w_4.jpeg",
			progress: 0
		},
		{
			status: "waiting",
			path: "/static/images/w_5.jpeg",
			progress: 0
		}
	]);

	// 选择
	// count: 可选择的数量
	function handleChoose(count) {
		uni.chooseImage({
			count,
			success: (res) => {
				console.log(res);
				const files = res.tempFiles;
				files.forEach((item, index) => {
					list.value.push({
						status: "waiting",
						path: item.path,
						file: item
					});
				});
			}
		});
	}

	// 上传
	function handleUpload() {
		list.value.forEach((item, index) => {
			onUpload(item, index);
		});
	}

	// 删除
	// index: 删除的索引
	// item: 删除的项
	function handleDelete(index, item) {
		list.value.splice(index, 1);
	}

	// 模拟上传
	function onUpload(item, index) {
		item.status = "uploading";

		let interval = setInterval(() => {
			// 随机0-1的数字
			const random = Math.random();
			if (item.progress >= 100) {
				clearInterval(interval);
				item.status = index % 2 === 0 ? "success" : "fail";
			} else {
				item.progress = item.progress + random;
			}
		}, 50);
	}
</script>

<style lang="scss" scoped></style>
